/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="app-container" ref="detector-container">
    <el-button style="margin-bottom:10px" type="primary" @click="onAdd">{{$t('edge.common.add')}}</el-button>
    <el-table class="tb-edit" ref="singleTable" :data="preemptList" v-loading.body="listLoading" element-loading-text="Loading" fit highlight-current-row v-clickoutside="cancelTable" :max-height="tableHeight" id="footerBtn">
      <el-table-column align="center" label='ID' min-width="40">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.level')" min-width="60">
        <template slot-scope="scope">
          <el-select v-model="scope.row.data.level" :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in levelOption"
              :key="item.value"
              :label="$t('edge.preempt.levelOption' + item.value)"
              :value="item.value">
            </el-option>
          </el-select>
          <span>{{$t('edge.preempt.levelOption' + scope.row.data.level)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.source')" min-width="100">
        <template slot-scope="scope">
            <el-input-number size="small" controls-position="right" :min="0" :max="65535" :step="1" v-model="scope.row.source"  style="width: 100px;"></el-input-number>
          <span>{{scope.row.source}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.type')">
        <template slot-scope="scope">
          <el-select v-model="scope.row.data.type" :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in typeOption"
              :key="item.value"
              :label="$t('edge.preempt.typeOption' + item.value)"
              :value="item.value">
            </el-option>
          </el-select>
          <span>{{$t('edge.preempt.typeOption' + scope.row.data.type)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.delay')" min-width="200">
        <template slot-scope="scope">
            <el-input-number size="small" controls-position="right" :min="0" :max="65535" :step="1" v-model="scope.row.delay"  style="width: 100px;"></el-input-number>
          <span>{{scope.row.delay}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.duration')" min-width="150">
        <template slot-scope="scope">
          <el-input-number size="small" controls-position="right" :min="0" :max="65535" :step="1" v-model="scope.row.duration"  style="width: 100px;"></el-input-number>
          <span>{{scope.row.duration}}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" :label="$t('edge.preempt.phase')" min-width="200">
        <template slot-scope="scope">
          <el-select v-model="scope.row.data.phase" :placeholder="$t('edge.common.select')" size="small" clearable>
            <el-option
              v-for="item in CallPhaseOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span>{{getPhaseById(scope.row.data.phase)}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" :label="$t('edge.preempt.omit')" min-width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.omit"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('edge.preempt.operation')">
        <template slot-scope="scope">
          <el-button type="text"  @click="handleDelete(scope.$index)">{{$t('edge.common.delete')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getPhaseDesc } from '@/utils/phasedesc.js'
import { mapState } from 'vuex'
const clickoutside = {
  // 初始化指令
  bind (el, binding, vnode) {
    function documentHandler (e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update () {},
  unbind (el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}
export default {
  name: 'detector',
  components: { },
  data () {
    return {
      tableHeight: 760,
      listLoading: false,
      CallPhaseOption: [],
      id: 1,
      typeOption: [{
        value: 0,
        label: this.$t('edge.preempt.typeOption0')
      }, {
        value: 1,
        label: this.$t('edge.preempt.typeOption1')
      }],
      levelOption: [{
        value: 1,
        label: 1
      }, {
        value: 2,
        label: 2
      }, {
        value: 3,
        label: 3
      }, {
        value: 4,
        label: 4
      }, {
        value: 5,
        label: 5
      }]
    }
  },
  directives: { clickoutside },
  filters: {
    statusFilter (status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  computed: {
    ...mapState({
      preemptList: state => state.globalParam.tscParam.preemptList
    })
  },
  created () {
    this.globalParamModel = this.$store.getters.globalParamModel
    this.init()
  },
  mounted: function () {
    var _this = this
    _this.$nextTick(function () {
      _this.tableHeight = _this.$refs['detector-container'].offsetHeight - 80
      window.onresize = function () {
        _this.tableHeight = _this.$refs['detector-container'].offsetHeight - 80
      }
    })
  },
  watch: {
    preemptList: function () {
      this.init()
    }
  },
  methods: {
    init () {
      this.initData()
      this.increaseId()
    },
    initData () {
      const phaseList = this.globalParamModel.getParamsByType('phaseList')
      this.CallPhaseOption = []
      for (let i = 0; i < phaseList.length; i++) {
        if (phaseList[i].controltype !== 99) {
          let pattern = {}
          var patternNum = phaseList[i].id
          var patternDescription
          if (phaseList[i].direction.length > 0 && phaseList[i].direction !== undefined) {
            patternDescription = patternNum + '-' + getPhaseDesc(phaseList[i].direction, this.$i18n.locale)
          } else {
            patternDescription = patternNum
          }
          pattern.value = patternNum
          pattern.label = patternDescription
          this.CallPhaseOption.push(pattern)
        }
      }
      let callPhaseList = this.CallPhaseOption.map(ele => ele.value)
      let preemptList = this.globalParamModel.getParamsByType('preemptList')
      for (let dtcl of preemptList) {
        dtcl.callphase = callPhaseList.includes(dtcl.callphase) ? dtcl.callphase : ''
      }
    },
    increaseId () { // 实现id在之前的基础上寻找最小的
      let preemptList = this.globalParamModel.getParamsByType('preemptList')
      let detectorIdList = preemptList.map(ele => ele.id)
      let i = preemptList.length - 1
      if (i >= 0) {
        for (let j = 1; j <= 72; j++) {
          if (!detectorIdList.includes(j)) {
            this.id = j
            return
          }
        }
      }
    },
    handleDelete (index) {
      this.$confirm(this.$t('edge.detector.deletetip'),
        this.$t('edge.common.alarm'), {
          confirmButtonText: this.$t('edge.common.confirm'),
          cancelButtonText: this.$t('edge.common.cancel'),
          type: 'warning'
        }).then(() => {
        this.globalParamModel.deleteParamsByType('preemptList', index, 1)
        this.$message({
          type: 'success',
          message: this.$t('edge.common.deletesucess')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('edge.common.deletecancel')
        })
      })
    },
    onAdd () {
      this.increaseId()
      var preemptInitData = {
        id: this.id,
        delay: 0,
        data: {
          level: 1,
          phase: 1,
          type: 0
        },
        source: 0,
        duration: 300,
        omit: 1
      }
      this.globalParamModel.addParamsByType('preemptList', preemptInitData)
      // this.id++
      // 重新排序相位数组
      let preemptList = this.globalParamModel.getParamsByType('preemptList')
      preemptList.sort(this.compareProperty('id'))
    },
    compareProperty (property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    cancelTable (e) {
      this.$refs.singleTable.setCurrentRow()
    },
    getPhaseById (id) {
      let phaselist = this.globalParamModel.getParamsByType('phaseList')
      if (id === undefined || id === '') return ''
      let phasedesc = phaselist.filter((item) => {
        return item.id === id
      })[0].direction
      // console.log(phasedesc)
      if (phasedesc.length === 0) return id
      let description = getPhaseDesc(phasedesc, this.$i18n.locale)
      return id + '-' + description
    }
  }
}
</script>

<style>
  /* * {
    margin: 0;
    padding: 0} */
  body {
      overflow: auto;
      font-weight: 400;
      -webkit-font-smoothing: antialiased;
    }
  .tb-edit .el-input {
    display: none
  }
  .tb-edit .current-row .el-input {
    display: block
  }
  .tb-edit .current-row .el-input+span {
    display: none
  }
  .tb-edit .el-select {
    display: none
  }
  .tb-edit .current-row .el-select {
    display: block
  }
  .tb-edit .current-row .el-select+span {
    display: none
  }
  .tb-edit .el-input-number {
    display: none
}
.tb-edit .current-row .el-input-number {
  display: block;
  margin-left: 30%;
}
.tb-edit .current-row .el-input-number+span {
  display: none
}
</style>
